<template>
  <!-- 面包屑 -->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 内容区域 -->
  <el-card class="card">
    <!-- 提示 -->
    <el-alert title="添加商品信息" type="info" center show-icon  :closable="false"/>

    <!-- 步骤条 -->
    <el-steps :active="stepActive" align-center class="step">
       <el-step title="基本信息"/>
       <el-step title="商品参数"/>
       <el-step title="商品属性"/>
       <el-step title="商品图片"/>
       <el-step title="完成"/>
    </el-steps>

    <!-- tab选项卡 -->
    <el-form ref="ruleFormRef" :model="state.form" label-width="auto" :rules="formRules.rules" label-position="top">
      <el-tabs tab-position="left" @tab-click="tabClick">
        <el-tab-pane label="基本信息">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="state.form.name" />
          </el-form-item>

          <el-form-item label="商品价格" prop="price">
            <el-input v-model.number="state.form.price" />
          </el-form-item>

          <el-form-item label="商品重量" prop="weight" >
            <el-input v-model.number="state.form.weight" />
          </el-form-item>

          <el-form-item label="商品数量" prop="num">
            <el-input v-model.number="state.form.num" />
          </el-form-item>

          <el-form-item label="商品分类" prop="state.category">
            <el-cascader clearable placeholder="---请选择---" v-model="state.form.jilianValue" :options="options" :props="{label: 'cat_name', value: 'cat_id', children: 'children'}" @focus="handleChange"/>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="基本参数">
          <el-form-item label="商品颜色" prop="color">
            <el-checkbox-group v-model="state.form.color">
              <el-checkbox label="红色" value="red"/>
              <el-checkbox label="绿色" value="green"/>
              <el-checkbox label="蓝色" value="blue"/>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="基本属性">
          <el-form-item label="商品长度" prop="goods_width">
            <el-radio-group v-model="state.form.goods_width">
              <el-radio label="大于5米" value="overFive"/>
              <el-radio label="小于5米" value="lessFive"/>
            </el-radio-group>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="商品图片">
          <el-form-item v-model="state.form.pic">
            <el-upload multiple :limit="5" list-type="picture" :headers="state.headerObj" action="/api" 
            :on-preview="handlePreview" :before-upload="handleBeforeUpload" :on-success="handleSuccess" :on-exceed="handleExeed" :on-remove="handleRemove" >
              <el-button type="primary">上传图片</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png文件不能超过100kb
                </div>
              </template>
            </el-upload>
          </el-form-item>

          <el-button :style="{marginTop: '100px'}" type="primary" class="btn btns" @click="onSubmit(ruleFormRef)">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>

  <el-dialog v-model="state.dialogVisible" title="图片预览">
    <img :src="state.bigPic"/>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { GetProductCategoryFnc } from '@/api/goods'
import { getCookie } from '@/utils/cookie'
const options = ref([]) // 级联所有的数据
const ruleFormRef = ref<FormInstance>()
const stepActive = ref(0) // 步骤条当前高亮

// 表单数据
const state = reactive({
  form: {name: '', price: 0, weight: 0, num: 0, jilianValue: [], color: [], goods_width: 0, pic: [] as any},
  headerObj: { Authorization: getCookie('token') }, // 上传图片需要token
  dialogVisible: false, // 图片预览盒子
  bigPic: '' // 图片预览
})
  
// 表单验证规则
const formRules = reactive({
  rules: {
    name: [
      {required: true, message: '请输入商品名', trigger: 'blur'},
      {min: 3, max: 5, message: '长度在3-5个字符', trigger: 'blur'}
    ],
    price: [
      {required: true, message: '请输入价格', trigger: 'blur'},
      {type: 'number', message: '价格为数字', trigger: 'blur'}
    ],
    weight: [
      {required: true, message: '请输入重量', trigger: 'blur'},
      {type: 'number', message: '价格为数字', trigger: 'blur'}
    ],
    num: [
      {required: true, message: '请输入数量', trigger: 'blur'},
      {type: 'number', message: '价格为数字', trigger: 'blur'}
    ],
    category: [
      {required: true, message: '请选择分类', trigger: 'blur'},
      // {type: 'number', message: '价格为数字', trigger: 'blur'}
    ],
    color: [
      {required: true, message: '请选择颜色', trigger: 'blur'},
      // {min: 1, max: 7, message: '长度在1-7个字符', trigger: 'blur'}
    ],
    goods_width: [
      {required: true, message: '请选择长度', trigger: 'blur'},
      // {min: 1, max: 7, message: '长度在1-7个字符', trigger: 'blur'}
    ]
  }
})

// 获得级联数据
const handleChange = async () => {
  const res = await GetProductCategoryFnc()
  if(res.data.meta.status === 200) {
    options.value = res.data.data
  }
}

// 图片上传成功
const handleSuccess = (response: any) => {
  if(response.meta.status === 200) {
    ElMessage({type: 'success', message: '上传图片成功', duration: 1000, onClose: () => {
      const info = { pics: response.data.tmp_path }
      state.form.pic.push(info)
    }})
  }
}

// 文件大小不能大于100kb
const handleBeforeUpload = (file: {size: number}) => {
  if(file.size / 1024 > 100) {
    ElMessage({type: 'error', message: '上传文件不能超过100kb', duration: 1000})
    return false
  }
}

// 文件数量超出
const handleExeed = (file: File[]) => {
  ElMessage({type: 'error', message: `您上传了${file.length}个文件, 最多只能上传5个`})
}

// 删除图片
const handleRemove = (uploadFile: {response: {data: {tmp_path: string}, meta: {status: number}}, status: string}) => { // 删除图片
  // 遇到的问题：before-remove、on-remove 钩子函数在选取文件的时候就调用了
  // 解决办法：在before-remove、on-remove 这两个钩子函数中加判断
  if (uploadFile.status === 'success') {
    const deletePaht = uploadFile.response.data.tmp_path
    const index = state.form.pic.findIndex((item: { pic: string }) => {
      return item.pic === deletePaht
    })
    state.form.pic.splice(index, 1)
  }
}

// 图片预览
const handlePreview = (file: any) => {
 state.dialogVisible = true
 if (file.response.meta.status === 200) {
  state.bigPic = file.response.data.url
 }
}

// 提交 方法API有问题 所以就没有用
const onSubmit = async (formEl: FormInstance | undefined) => {
  if(!formEl) return 
  await formEl.validate(async (valid) => {
    console.log(state.form)
    if(valid) {
      console.log(1)
      stepActive.value = 4
    }
  })
}

// 步骤条高亮
const tabClick = (pane: any) => {
  console.log(pane.index)
  stepActive.value = parseInt(pane.index)
}

</script>


<style lang="scss" scoped>
.card{
   margin-top: 20px;
   .step{
    margin: 30px 0;
    ::v-deep .el-step__title{
      font-size: 13px;
    }
   }
}
</style>